package com.mycity.dao;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.mycity.bean.Report;
import com.mycity.mapper.ReportRowMapper;
import com.mycity.mapper.PostRowMapper;
import com.mycity.mapper.CommentRowMapper;
import com.mysql.jdbc.PreparedStatement;

public class ReportDao extends RDSDao{
	
	public int reportContent(final int contentType, final int contentId, final int reporterId, final int reportedId, final String reportDate){
		final String insertSQL = "INSERT INTO Report(contentType, contentId, reporterId, reportedId, reportDate) VALUES(?,?,?,?,?)";

		KeyHolder holder = new GeneratedKeyHolder();

		this.getTemplate().update(new PreparedStatementCreator() {           


			@Override
			public java.sql.PreparedStatement createPreparedStatement(
					Connection con) throws SQLException {
				PreparedStatement ps = (PreparedStatement) con.prepareStatement(insertSQL, Statement.RETURN_GENERATED_KEYS);
				ps.setInt(1, contentType);
				ps.setInt(2, contentId);
				ps.setInt(3, reporterId);
				ps.setInt(4, reportedId);
				ps.setString(5,  reportDate);	
				return ps;
			}
		}, holder);

		int reportId = holder.getKey().intValue();

		return reportId;
		
	}
	
	public List<Report> getReports(int contentId, int contentType){
		
		Object params[] = { contentId };
		if(contentType==1){	
			List<Report> reports = this.getTemplate().query("SELECT * from Report where contentId=? AND contentType=1", params, new ReportRowMapper()); 
			return reports;
		}
		
		else{
			List<Report> reports = this.getTemplate().query("SELECT * from Report WHERE contentId=? AND contentType=2", params, new ReportRowMapper()); 			
			return reports;
		}
	}
	
	public boolean reportControl(int contentId, int contentType){
		Object params[] = { contentId,contentType };
		List<Report> check = this.getTemplate().query("SELECT * from Report WHERE contentId=? AND contentType=?", params, new ReportRowMapper());
		
		if(check.size()>=3){
			return true;
		}
		else{
			return false;
		}
		
	}
	
	public void deleteFromReportTable(int contentId, int contentType){
		Object params[] = { contentId, contentType };
		this.getTemplate().update("DELETE FROM Report WHERE contentId=? AND contentType=?", params);
	}
	
}

	